package com.hongri.recyclerview.widget;

import android.content.Context;
import android.os.Looper;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

import com.hongri.recyclerview.utils.Logger;

/**
 * @author：zhongyao on 2016/11/1 15:40
 * @description:Scroller测试
 *
 * 继承自ViewGroup的自定义view 需要自己处理ViewGroup的测量、布局，同时自己处理自View的测量、布局。
 */

public class ScrollerLayout extends ViewGroup {
    /**
     * 用于完成滚动操作的实例
     */
    private Scroller mScroller;

    /**
     * 判定为拖动的最小移动像素数
     */
    private int mTouchSlop;

    /**
     * 手机按下时的屏幕坐标
     */
    private float mXDown;

    /**
     * 手机当时所处的屏幕坐标
     */
    private float mXMove;

    /**
     * 上次触发ACTION_MOVE事件时的屏幕坐标
     */
    private float mXLastMove;

    /**
     * 界面可滚动的左边界
     */
    private int leftBorder;

    /**
     * 界面可滚动的右边界
     */
    private int rightBorder;

    /**
     * 测速
     */
    private VelocityTracker mVelocityTracker;

    public ScrollerLayout(Context context) {
        super(context);
        Logger.d("ScrollerLayout--1");
    }

    public ScrollerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        Logger.d("ScrollerLayout--2");
        init(context);
    }

    public ScrollerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Logger.d("ScrollerLayout--3");
        init(context);
    }


    private void init(Context context) {
        // 第一步，创建Scroller的实例
        mScroller = new Scroller(context);
        ViewConfiguration configuration = ViewConfiguration.get(context);
        // 获取TouchSlop值
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);

        mVelocityTracker = VelocityTracker.obtain();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Logger.d("onMeasure");
        int childCount = getChildCount();
        float marginLeft = getLeft();
        float paddingLeft = getPaddingLeft();
        Logger.d("onMeasure----marginLeft:"+marginLeft+" paddingLeft："+paddingLeft);
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            float childViewMarginLeft = childView.getLeft();
            float childViewPaddingLeft = childView.getPaddingLeft();
            Logger.d("onMeasuer--------childViewMarginLeft:"+childViewMarginLeft+" childViewPaddingLeft:"+childViewPaddingLeft);
            // 为ScrollerLayout中的每一个子控件测量大小
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            Logger.d("onLayout");
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                int childViewPaddingLeft = childView.getPaddingLeft();
                int childViewPaddingright = childView.getPaddingRight();
                Logger.d("onLayout--------"+" childViewPaddingLeft:"+childViewPaddingLeft+" childViewPaddingright"+childViewPaddingright);
                // 为ScrollerLayout中的每一个子控件在水平方向上进行布局
                childView.layout(i * childView.getMeasuredWidth()+childViewPaddingLeft, 0, (i + 1) * childView.getMeasuredWidth(), childView.getMeasuredHeight());
            }
            // 初始化左右边界值
            leftBorder = getChildAt(0).getLeft();
            rightBorder = getChildAt(getChildCount() - 1).getRight();
            Logger.d("leftBorder:" + leftBorder + " rightBorder:" + rightBorder);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mXDown = ev.getRawX();
                Logger.d("mXDown: " + mXDown);
                mXLastMove = mXDown;
                break;
            case MotionEvent.ACTION_MOVE:
                mXMove = ev.getRawX();
                Logger.d("mXMove:" + mXMove);
                float diff = Math.abs(mXMove - mXDown);
                mXLastMove = mXMove;
                // 当手指拖动值大于TouchSlop值时，认为应该进行滚动，拦截子控件的事件
                if (diff > mTouchSlop / 2) {
                    Logger.d("onInterceptTouchEvent---拦截子控件的事件，由ScrollerLayout来消费" + " diff==" + diff);
                    return true;
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //Add a user's movement to the tracker.
        mVelocityTracker.addMovement(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:

                mVelocityTracker.computeCurrentVelocity(500);
                float xVelocity0 = mVelocityTracker.getXVelocity();
                Logger.d("xVelocity0:" + xVelocity0);

                //触摸点相对于屏幕的坐标
                mXMove = event.getRawX();
                //触摸点相对于按钮的坐标
                float getX = event.getX();
                Logger.d("onTouchEvent--mMove:" + mXMove+" getX:"+getX);

                int scrolledX = (int) (mXLastMove - mXMove);
                Logger.d("onTouchEvent--scrolledX:" + scrolledX);
                Logger.d("onTouchEvent--getScrollX():" + getScrollX());
                Logger.d("onTouchEvent--leftBorder:" + leftBorder);
                if (getScrollX() + scrolledX < leftBorder) {
                    Logger.d("scrollTo(leftBorder, 0);");
                    scrollTo(leftBorder, 0);
                    return true;
                } else if (getScrollX() + getWidth() + scrolledX > rightBorder) {
                    scrollTo(rightBorder - getWidth(), 0);
                    return true;
                }
                scrollBy(scrolledX, 0);
                mXLastMove = mXMove;
                break;
            case MotionEvent.ACTION_UP:
                //计算出手指滑动速度
                mVelocityTracker.computeCurrentVelocity(500);
                float xVelocity = mVelocityTracker.getXVelocity();
                Logger.d("xVelocity:" + xVelocity);
                // 当手指抬起时，根据当前的滚动值来判定应该滚动到哪个子控件的界面
                int targetIndex = (getScrollX() + getWidth() / 2) / getWidth();
                if (Math.abs(xVelocity) >= 50) {
                    targetIndex = xVelocity > 0 ? targetIndex - 1 : targetIndex + 1;
                    if (targetIndex > getChildCount() -1){
                        targetIndex = getChildCount() - 1 ;
                    }else if (targetIndex < 0){
                        targetIndex = 0;
                    }
                }
                int dx = targetIndex * getWidth() - getScrollX();
                // 第二步，调用startScroll()方法来初始化滚动数据并刷新界面
                mScroller.startScroll(getScrollX(), 0, dx, 0, 1000);
                invalidate();
                mVelocityTracker.clear();
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void computeScroll() {
        // 第三步，重写computeScroll()方法，并在其内部完成平滑滚动的逻辑
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            invalidate();
        }
    }


}
